// shadcn 主题
import "@blocknote/shadcn/style.css";
// 语言包
import { zh } from "@blocknote/core/locales";
import {
  BlockNoteSchema,
  defaultBlockSpecs,
  defaultInlineContentSpecs,
  filterSuggestionItems,
  PartialBlock
} from "@blocknote/core";
import { SuggestionMenuController, useCreateBlockNote, type DefaultReactSuggestionItem } from "@blocknote/react";

import { useQueryClient } from "@tanstack/react-query";
import { useMemo } from "react";
import { WebsocketProvider } from "y-websocket";
import * as Y from "yjs";

import { Mention } from "@/blocks/mention";

import * as srv from "@/services";
import { User } from "@/types/api";

import { cursorRender } from "./cursorRender";
import { BlockNoteView } from "@blocknote/shadcn";

interface DocEditorProps {
  pageId: string;
  initialContent?: PartialBlock[];
  doc: Y.Doc;
  provider: WebsocketProvider;
}

const schema = BlockNoteSchema.create({
  inlineContentSpecs: {
    ...defaultInlineContentSpecs,
    mention: Mention
  },
  blockSpecs: {
    ...defaultBlockSpecs
  }
});

export function DocEditor(props: DocEditorProps) {
  const { pageId, doc, provider } = props;
  const queryClient = useQueryClient();
  const currentUser = queryClient.getQueryData<User>(["currentUser"]);

  const randomColor = useMemo(() => {
    const storedColor = sessionStorage.getItem("user-color");
    if (storedColor) {
      return storedColor;
    }
    const color = `#${Math.floor(Math.random() * 0xffffff)
      .toString(16)
      .padStart(6, "0")}`;
    sessionStorage.setItem("user-color", color);
    return color;
  }, []);

  const editor = useCreateBlockNote(
    {
      schema,
      dictionary: zh,

      collaboration: {
        provider,
        fragment: doc.getXmlFragment(`document-store-${pageId}`),
        user: {
          name: currentUser?.username ?? "",
          color: randomColor
        },
        renderCursor: cursorRender
      }
    },
    [pageId, provider, doc, currentUser]
  );

  const getMentionMenuItems = async (e: typeof editor, pageId?: string): Promise<DefaultReactSuggestionItem[]> => {
    const items: DefaultReactSuggestionItem[] = [];
    // 获取远程页面
    const res = await srv.fetchPageList();
    const pages = res.data.pages;

    for (const page of pages) {
      if (page.pageId !== pageId) {
        items.push({
          icon: <span>{page.emoji}</span>,
          title: page.title,
          onItemClick: () => {
            e.insertInlineContent([
              {
                type: "mention",
                props: {
                  id: page.pageId,
                  title: page.title,
                  icon: page.emoji
                }
              },
              " "
            ]);
          }
        });
      }
    }

    return items;
  };

  return (
    <BlockNoteView editor={editor} theme="light">
      <SuggestionMenuController
        triggerCharacter="@"
        getItems={async query => {
          const items = await getMentionMenuItems(editor, pageId);
          return filterSuggestionItems(items, query);
        }}
      />
    </BlockNoteView>
  );
}
